<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="pingpong.png">
    <link rel="stylesheet" type="text/css" href="pingpong.css">
    <title>Async Servlet</title>
</head>
<body>

<div id="field">
    <div id="player2" class="player"></div>
    <div id="player1" class="player"></div>
    <div id="ball"></div>
</div>
<div id="scoreBoard">
    0 - 0
</div>

<script type="text/javascript" src="jQuery/jquery-1.9.1.js"></script>

<script type="text/javascript" >
    (function() {

        var $field = $('#field');
        var $ball = $('#ball');
        var $player1 = $('#player1');
        var $player2 = $('#player2');
        var $scoreBoard = $('#scoreBoard');
        var playerPosition = 300;
        var gameId = null;

        function callback(player1Left, player2Left, ballTop, ballLeft, score1, score2) {
            $ball.css('left', ballLeft);
            $ball.css('top', ballTop);
            $player1.css('left', player1Left);
            $player2.css('left', player2Left);
            $scoreBoard.text(score1 + ' - ' + score2);
        };

        $field.mousemove(function(event) {
            playerPosition = event.pageX
        });

        function go(){
            var url = "pingpongasync";
            if (gameId) {
                url += "?id=" + gameId + "&x=" + playerPosition;
            }
            var request =  new XMLHttpRequest();
            request.open("GET", url, true);
            request.setRequestHeader("Content-Type", "application/x-javascript;");
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                    if (request.status == 200){
                        if (request.responseText) {
                            if (!gameId) {
                                gameId = request.responseText;
                            } else {
                                var params = request.responseText.split(',');
                                callback(parseInt(params[0]), parseInt(params[1]), parseInt(params[2])
                                        , parseInt(params[3]), parseInt(params[4]), parseInt(params[5]))
                            }
                        }
                    }
                    go();
                }
            };
            request.send(null);
        }
        go();
    })();
</script>

</body>
</html>